<template>
    <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" ref="dragTable" border class="t1" v-if="showTable" default-expand-all>
        <el-table-column prop="date" label="Date" sortable />
        <el-table-column prop="name" label="Name" sortable />
        <el-table-column prop="address" label="Address" sortable />
    </el-table>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, ref } from 'vue'
import Sortable from 'sortablejs'

interface User {
    id: number
    date: string
    name: string
    address: string
    hasChildren ? : boolean
    children ? : User[]
}

const dragTable = ref(null)

let ywArr = ref < any > ([]);
let tableData = ref < any > ([{
        id: 1,
        date: '1',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
    },
    {
        id: 2,
        date: '2',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
    },
    {
        id: 3,
        date: '3',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
        children: [{
                id: 31,
                date: 'children1',
                name: 'wangxiaohu',
                address: 'No. 189, Grove St, Los Angeles',
            },
            {
                id: 32,
                date: 'children2',
                name: 'wangxiaohu',
                address: 'No. 189, Grove St, Los Angeles',
            },
        ],
    },
    {
        id: 4,
        date: '4',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
    },
]);
let showTable = ref < boolean > (true);

// 转成一维数组
const flattenArrayWithParentId = (arr: any, parentId = null) => {
    let result: any = [];
    const flatten = (item: any, parent: any) => {
        result.push({
            id: item.id,
            parentId: parent ? parent.id : null,
            date: item.date,
            name: item.name,
            address: item.address
        });
        if (item.children) {
            item.children.forEach((child: any) => flatten(child, item));
        }
    };

    arr.forEach((item: any) => flatten(item, parentId));

    return result;
}


// 转成父子级结构
const reconstructHierarchy = (arr: any) => {
    const map: any = {};
    const result: any = [];
    arr.forEach((item: any) => {
        map[item.id] = { ...item, children: [] };
    });
    arr.forEach((item: any) => {
        if (item.parentId !== null) {
            map[item.parentId].children.push(map[item.id]);
        } else {
            result.push(map[item.id]);
        }
    });
    return result;
};

// 创建sortable实例
const initSortable = () => {
    const tableEl = document.querySelector('.t1 .el-table__body-wrapper tbody')
    new Sortable(tableEl, {
        animation: 150,
        draggable: '.el-table__row',
        fallbackOnBody: true,
        // 结束拖拽
        onEnd: (evt: any) => {
            let { oldIndex, newIndex } = evt;
            let tableDataCopy = ywArr.value.concat();
            let drugItem = tableDataCopy.splice(oldIndex, 1);
            tableDataCopy.splice(newIndex, 0, drugItem[0]);
            let result = reconstructHierarchy(tableDataCopy)
            console.log(result,'拖拽成功');
            
            showTable.value = false;
            tableData.value = result;
            ywArr.value = flattenArrayWithParentId(tableData.value);
            console.log(ywArr.value,'拖拽成功1111');
            
            setTimeout(() => {
                showTable.value = true;
                nextTick(() => {
                    tableData.value = reconstructHierarchy(ywArr.value)
                    initSortable();
                })
            })
        },
    });
}

onMounted(() => {
    initSortable();
    ywArr.value = flattenArrayWithParentId(tableData.value);
})
</script>
